package com.ruoyi.client.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.client.pojo.form.OrderInsertForm;
import com.ruoyi.client.pojo.vo.OrderVo;
import com.ruoyi.client.service.IClientOrderService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Anonymous  //接口允许匿名访问
@RestController
@RequestMapping("/order")
public class ClientOrderController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(ClientOrderController.class);
    @Resource
    private IClientOrderService orderService;

    // 创建订单
    @PostMapping("/create")
    public AjaxResult create(@RequestBody @Valid OrderInsertForm form){
        // 登录验证
        StpUtil.checkLogin();
        // 调用服务层
        if(orderService.create(form)){
            return AjaxResult.success();
        }else{
           return AjaxResult.error();
        }
    }

    // 查询登录用户的订单列表
    @GetMapping("/list")
    public AjaxResult list(){
        // 当前登录用户,未登录会抛出例外NotLoginException
        Long userId = StpUtil.getLoginIdAsLong();
        // 调用服务层
        List<OrderVo> orderVoList = orderService.list(userId);
        return AjaxResult.success(orderVoList);
    }

    // 查询订单详情ById
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam Long id){
        // 登录验证
        StpUtil.checkLogin();
        logger.info("用户Id:" + StpUtil.getLoginIdAsInt() +  "/Token:" + StpUtil.getTokenValue());
        // 调用服务层
        OrderVo orderVo = orderService.selectById(id);

        return AjaxResult.success(orderVo);
    }

    // 取消订单
    @PostMapping("/cancel")
    public AjaxResult cancel(@RequestParam Long id){
        // 登录验证
        StpUtil.checkLogin();
        // 调用服务层
        if(orderService.cancel(id)){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }

    // 删除订单
    @PostMapping("/delete")
    public AjaxResult delete(@RequestParam Long id){
        // 登录验证
        StpUtil.checkLogin();
        // 调用服务层
        if(orderService.delete(id)){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }
}
